package com.tsky.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 
 * @author cainiao
 * @类描述：FreeMarker格式化
 * @date：2010-3-6
 */
public class FtlUtil {

	public static void main(String[] args) throws Exception {
		Map data = new HashMap();
		
		List strlist = new ArrayList();
		strlist.add("aa");
		strlist.add("bb");
		strlist.add("cc");
		strlist.add("dd");

		data.put("strlist", strlist);

		data.put("htag", "<h2>我是右边模块</h2>");
		
		data.put("x", 1);
		data.put("y", 2);
		
		data.put("date", new Date());
		data.put("book", 20);
		
		String htmlFile = "webroot/index.html";
		String dir = "bin/freemarker";
		String template = "index.ftl";
		
		long begin = System.currentTimeMillis();
		
		buildHtml("UTF-8", data, dir, template, htmlFile);
		
		long end = System.currentTimeMillis();
		long time = end - begin;
		System.out.println(time);
	}

	/**
	 * 
	 * @author：cainiao
	 * @方法描述：FreeMarker静态化
	 * @date: 2010-3-16
	 * @param code
	 * @param data
	 * @param dir
	 * @param template
	 * @param htmlFile
	 */
	public static void buildHtml(String code, Map data, String dir, String template,
			String htmlFile) {
		Configuration cfg = new Configuration();
		try {
			cfg.setDirectoryForTemplateLoading(new File(dir));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 模板文件所在的目录
		cfg.setDefaultEncoding(code);

		Template t = null;
		try {
			t = cfg.getTemplate(template);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 得到模板文件
		Writer out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(htmlFile), code);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			t.process(data, out);
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 开始转化处理
	}

}
